/* 
 * Copyright 2013 Sébastien Mouquet.
 * 
 * This file is part of ECovoiturage.
 * 
 * ECovoiturage is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ECovoiturage is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ECovoiturage. If not, see http://www.gnu.org/licenses/.
 */
package com.smouquet.ecovoiturage;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.smouquet.ecovoiturage.core.bean.Config;
import com.smouquet.ecovoiturage.core.exception.ConfigIOException;
import com.smouquet.ecovoiturage.core.service.ConfigService;

/**
 *
 * @author sebastien.mouquet
 */
public class ApplicationContext
{
    private static final ApplicationContext INSTANCE = new ApplicationContext();
    
    public static void init() throws ConfigIOException
    {
        // Création de l'injecteur par défaut
        INSTANCE.injector = Guice.createInjector(new ApplicationModule());
        
        // Chargement de la configuration
        ConfigService service = getInstance(ConfigService.class);
        INSTANCE.config = service.loadConfig();
        
        // Si la configuration est présente, on recréer
        // l'injecteur en transmettant la configuration
        if(INSTANCE.config != null) {
            INSTANCE.injector = Guice.createInjector(new ApplicationModule(INSTANCE.config));
        }
    }
    
    
    public static Injector getInjector()
    {
        return INSTANCE.injector;
    }
    
    public static <T> T getInstance(Class<T> type)
    {
        return INSTANCE.injector.getInstance(type);
    }
    
    public static Config getConfig()
    {
        return INSTANCE.config;
    }
    
    
    private Injector injector;
    private Config config;
    
    private ApplicationContext() {}
}
